import React, { useState,useEffect } from 'react';  
import { Card, Button, Modal, Table,Space,Form,Input,Row,Col,Select, message,Upload   } from 'antd';  
import { UploadOutlined } from '@ant-design/icons';  
import { EditOutlined, DeleteOutlined,PlusOutlined,DownloadOutlined } from '@ant-design/icons';  
import { listRemark} from "@/api/modules/report";
import {useTranslation} from 'react-i18next';
import {download} from "@/utils/request";
import { createReport,editProduct,separatedFm,addFm,editFm,separatedFix,separatedCreateReport,subjectTestResult,updateSubjectTestResult,mixedfm,mixedFix,mixedCreateReport,getRmInciResult,saveSafetyRmInciResult,batchSaveRmInciResult,updateDataResult,uploadRemark,uploadRemarkUpdate,delRemark,refreshResult} from "@/api/modules/jhreport";
const Step5 = ({ formData,productId,onUploadSuccess }) => {  
  const { t } = useTranslation();
  const [newFormData, setNewFormData] = useState({});  
  const [formData1, setFormData] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false); 
  const [Title, setTitle] = useState("")  
  const [form] = Form.useForm();  
  const [fileList, setFileList] = useState([]); 
  useEffect(()=>{
    getData()
  },[])

  const getData = () =>{
    const query = {
        pageNum: 1,
        pageSize: 9999,
        productId: productId,
      }
      listRemark(query).then(res=>{
       const data = res.data.rows
       setFormData(data)
      })
  }

  const showModal = () => {  
    setIsModalVisible(true);  
  };  

  
  const handleOk = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form.getFieldsValue();  
      const { file } = values;  
    let formData = new FormData();
    const data = form.getFieldsValue()
   if(values.file==null || values.file == undefined || values.file == ""){
        formData.append("file", null);
    }else{
        const file1 = values.file[0].originFileObj
        formData.append('file',file1); // 假设file.file是选中的文件对象  
    }
    if(Title=='新增/New'){
        formData.append("productId", productId);
    }else{
        formData.append("id", data.id);
    }
   
    formData.append("type", data.type);
    formData.append("name", data.remarkName);
    if(Title=='新增/New'){
        //新增
        uploadRemark(formData).then(res=>{
            message.success("Success")
             getData()
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
           
        })
    }else{
        //修改
        uploadRemarkUpdate(formData).then(res=>{
            message.success("Success")
             getData()
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
       })
    }

  
    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  
  
  const handleCancel = () => {  
    setIsModalVisible(false);  
  };  
  

  // 假设formData是一个对象数组，每个对象包含key和value字段  
  const renderFormData = () => {  
    return formData.map((item, index) => (  
      <div key={index}>  
         {item}  
      </div>  
    ));  
  };  

  const columns = [  
    {  
      title: t('name'),  
      dataIndex: 'remarkName',  
      key: 'remarkName',  
    },  
    {  
      title: t('type'),  
      dataIndex: 'type',  
      key: 'type',  
    },  
    {  
        title: t('template.file'),  
        dataIndex: 'filePath',  
        key: 'filePath',  
      }, 
    {  
      title: t('status'),  
      dataIndex: 'status',  
      key: 'status',  
    },  
    {  
      title: t('action'),  
      key: 'action',  
      render: (text, record) => (  
        <>  
          <Button type="link" onClick={() => handleEdit(record)}>  
            <EditOutlined />  {t('edit')}   
          </Button>  
          <Button type="link" danger onClick={() => handleDelete(record.id)}>  
            <DeleteOutlined />  {t('delete')}  
          </Button>  
          <Button type="link"  onClick={() => handleDownload(record)}>  
            <DownloadOutlined />  {t('download')}  
          </Button> 
        </>  
      ),  
    },  
  ];  

  const handleEdit = (record) => {  
    setTitle("修改/Edit")
    console.log(record,'record')
    form.setFieldsValue({ ...record });  
    setIsModalVisible(true);  
    // 这里可以添加打开模态框并显示编辑表单的逻辑  
  };  
  
  const handleDelete = (key) => {  
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        delRemark(key).then(res=>{
            message.success("Success")
            getData()
        }) 
      },  
    });  
  };

  const getLastSegment =(str) =>{  
    const segments = str.split('/');  
    return segments.pop();  
  }  

  const handleDownload = (row) =>{
    let name = getLastSegment(row.filePath)
    download("/safety/remark/downloadRemark?id="+row.id, {
   
    }, `${name}`)
   
  }

  const handleAdd = () =>{
    form.resetFields()
    setTitle("新增/New")
    showModal()
  }

  const handleSubmit = async () => {  
    onUploadSuccess('5','')
}

const beforeUpload = (file) => {  
   
  };  

const handleFileChange = (info) => { 
    console.log(info,'info') 
    form.setFieldsValue({  
        file: info.file,  
      }); 
  };  
  
  
  return (  
    <div>  
      <Card title="附录">  
        {/* 循环显示formData内容 */}  
        {renderFormData()}  
      </Card>  
      <Card style={{ marginTop: '16px' }}>
      <Row >  
        <Col span={24}> {/* 假设使用24栅格系统 */}  
          <Button size='small' type="primary" onClick={handleAdd}>  
            <PlusOutlined /> {t("add")}  
          </Button>  
        </Col>  
      </Row>  
  
      <Row style={{ marginTop: '16px' }}> {/* 使用行和列来创建表格上方的空间 */}  
        <Col span={24}>  
          <Table 
            columns={columns}  
            dataSource={formData1}  
            pagination={false}  
          />  
        </Col>  
      </Row>  
      </Card>
      <Form  onFinish={handleSubmit} layout="vertical">  
      <div style={{marginTop:'2%'}}></div>
      <Row justify="center" align="middle">
        <Col>  
            <Form.Item>  
            <Button type="primary" size='small'  htmlType="submit">  
            {t('report.Next')}  
            </Button> 
            </Form.Item> 
            </Col> 
           </Row>
        </Form>
        <Modal  
          title={Title}
          visible={isModalVisible}  
          onOk={handleOk}  
          onCancel={handleCancel}  
          destroyOnClose
        >  
          <Form form={form} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled />  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item  
              name="remarkName"  
              label={t('name')} 
              rules={[{ required: true, message: '请输入名称！' }]}  
            >  
              <Input/>  
            </Form.Item>  
            <Form.Item  
              name="type"  
              label={t('type')}
              rules={[{ required: true, message: '请选择类型！' }]}  
            >  
              <Select>
                <Select.Option value="固定附录">固定附录</Select.Option>
                <Select.Option value="风险物质检测">风险物质检测</Select.Option>
                <Select.Option value="质量规格证明">质量规格证明</Select.Option>
              </Select>
            </Form.Item>  
            <Form.Item  
                name="file"  
                label={t('template.file')}
                valuePropName="fileList"  
                getValueFromEvent={({ fileList }) => fileList}  
            >  
                <Upload  
                customRequest={({ file, onSuccess, onError }) => {  
                    // 这里是自定义上传逻辑，您可以根据实际需求实现上传逻辑  
                    // 例如，使用axios发送POST请求上传文件  
                    // 注意：这里的逻辑与表单提交时的文件上传是独立的，如果只需要在表单提交时上传，可以省略这部分  
                }}  
                beforeUpload={beforeUpload}  
                onChange={handleFileChange} 
                >  
                <Button icon={<UploadOutlined />}>{t('selectUpload')}</Button>  
                </Upload>  
            </Form.Item>
          </Form>  
        </Modal>  
    </div>  
  );  
};  
  
export default Step5;